//
//  PlaylistDBManager.swift
//  readtool
//
//  Created by Wan Jiading on 2017/7/31.
//  Copyright © 2017年 DAD. All rights reserved.
//	我的歌单数据库管理器

import UIKit
import FMDB

class PlaylistDBManager: NSObject {
	
	static var dbQueue = DBManager.getDBQueue()
	
	/// 获取播放列表
	class func getPlaylist(_ memberUUID: String, _ playlistType: PlaylistType, completion: (PlaylistModel?, String?)->()) {
		dbQueue.inDatabase { (db) in
			let sql = "SELECT * FROM t_playlist WHERE member_uuid = '\(memberUUID)' AND type = '\(playlistType.rawValue)';"
			let playlistModel = PlaylistModel()
			if let rs = db.executeQuery(sql, withArgumentsIn: []) {
				if rs.next() {
					playlistModel.code = rs.int(forColumn: "code")
					playlistModel.id = rs.string(forColumn: "id")
					if let typeStr = rs.string(forColumn: "type") {
						if let type = PlaylistType(rawValue: typeStr) {
							playlistModel.type = type
						}
					}
					playlistModel.version = rs.string(forColumn: "version")
					playlistModel.name = rs.string(forColumn: "name")
					playlistModel.member_uuid = rs.string(forColumn: "member_uuid")
					playlistModel.pic_url = rs.string(forColumn: "pic_url")
				}
				completion(playlistModel, nil)
				rs.close()
			} else {
				ExceptionLog("执行获取 Playlist 出错 \(sql)")
				completion(nil, "执行获取 Playlist 出错")
			}
		}
	}
	
	class func getCount(_ memberUUID: String, completion:(Int32, String?)->()) {
		dbQueue.inDatabase { (db) in
			let sql = "SELECT count(*) as count FROM t_playlist WHERE member_uuid = '\(memberUUID)';"
			if let rs = db.executeQuery(sql, withArgumentsIn: []) {
				if rs.next() {
					let count = rs.int(forColumn: "count")
					completion(count, nil)
				}
				rs.close()
			}
		}
	}
	
	/// 更新版本
	///
	/// - Parameters:
	///   - playlistModel: 必须包含 member_uuid, type, id, version
	class func updatePlaylistVersion(_ playlistModel: PlaylistModel, completion: execUpdateCompletion) {

		if (!authVersion(playlistModel.version, completion: completion)) { return }
		if (!authType(playlistModel.type, completion: completion)) { return }
		if (!authId(playlistModel.id, completion: completion)) { return }
		if (!authmemberUUID(playlistModel.member_uuid, completion: completion)) { return }
		
		dbQueue.inDatabase { (db) in
			let sql = "UPDATE t_playlist SET version = ? WHERE member_uuid = ? AND type = ? AND id = ?;"
			let success = db.executeUpdate(sql,
							withArgumentsIn: [playlistModel.version!,
							                  playlistModel.member_uuid!,
											  playlistModel.type.rawValue,
											  playlistModel.id!])
			if success {
				completion(true, nil)
			} else {
				completion(false, "执行t_playlist 更新数据出错")
				ErrorLog("执行t_playlist 更新数据出错\n\(sql)")
			}
		}
	}
	
	/// 删除某个playlist
	///
	/// - Parameters:
	///   - playlistModel: 必须包含 member_uuid, type, id
	class func deletePlaylist(_ playlistModel: PlaylistModel, completion: execUpdateCompletion) {
		
		if (!authType(playlistModel.type, completion: completion)) { return }
		if (!authId(playlistModel.id, completion: completion)) { return }
		if (!authmemberUUID(playlistModel.member_uuid, completion: completion)) { return }
		
		dbQueue.inDatabase { (db) in
			let sql = "DELETE FROM t_playlist WHERE member_uuid = ? AND type = ? AND id = ?;"
			let success = db.executeUpdate(sql,
							withArgumentsIn: [playlistModel.member_uuid!,
							                  playlistModel.type.rawValue,
							                  playlistModel.id!])
			if success {
				completion(true, nil)
			} else {
				completion(false, "执行t_playlist 删除数据出错")
				ErrorLog("执行t_playlist 删除数据出错\n\(sql)")
			}
		}
	}
	
	/// 添加1个playlist
	///
	/// - Parameters:
	///   - playlistModel: 必须包含 member_uuid, type, id, name, version
	class func addPlaylist(_ playlistModel: PlaylistModel, completion: execUpdateCompletion) {
		
		if (!authVersion(playlistModel.version, completion: completion)) { return }
		if (!authType(playlistModel.type, completion: completion)) { return }
		if (!authId(playlistModel.id, completion: completion)) { return }
		if (!authmemberUUID(playlistModel.member_uuid, completion: completion)) { return }
		if (!authName(playlistModel.name, completion: completion)) { return }

		dbQueue.inDatabase { (db) in
			let sql = "INSERT INTO t_playlist (id, name, member_uuid, type, pic_url, version, other_data)" +
					  "VALUES" +
					  "(?, ?, ?, ?, ?, ?, ?);"
			let success = db.executeUpdate(sql,
						    withArgumentsIn: [playlistModel.id!,
											  playlistModel.name!,
							                  playlistModel.member_uuid!,
							                  playlistModel.type.rawValue,
							                  playlistModel.pic_url ?? "",
							                  playlistModel.version!,
							                  ""])
			if success {
				completion(true, nil)
			} else {
				completion(false, "执行t_playlist 插入数据出错")
				ErrorLog("执行t_playlist 插入数据出错\n\(sql)")
			}
		}
	}
	
	
	// MARK: - 创建表
	
	class func createPlaylistTable() {
		dbQueue.inDatabase { (db) in
			let sql = "CREATE TABLE IF NOT EXISTS t_playlist (" +
				"'code' INTEGER PRIMARY KEY AUTOINCREMENT," +
				"'id' TEXT," +
				"'member_uuid' TEXT," +
				"'type' TEXT," +
				"'name' TEXT," +
				"'pic_url' TEXT," +
				"'version' TEXT," +
				"'other_data' TEXT);"
			if !db.executeUpdate(sql, withArgumentsIn: []) {
				ExceptionLog("t_playlist 创建失败")
			}
		}
	}
	
	// MARK: - 验证字段是否合法
	
	private class func authVersion(_ version: String?, completion: execUpdateCompletion) -> Bool {
		if version != nil {
			return true
		}
		completion(false, "version 为空")
		return false
	}
	private class func authType(_ type: PlaylistType?, completion: execUpdateCompletion) -> Bool {
		if type != nil {
			return true
		}
		completion(false, "type 为空")
		return false
	}
	private class func authId(_ id: String?, completion: execUpdateCompletion) -> Bool {
		if id != nil {
			return true
		}
		completion(false, "id 为空")
		return false
	}
	private class func authmemberUUID(_ memberUUID: String?, completion: execUpdateCompletion) -> Bool {
		if memberUUID != nil {
			return true
		}
		completion(false, "memberUUID 为空")
		return false
	}
	private class func authName(_ name: String?, completion: execUpdateCompletion) -> Bool {
		if name != nil {
			return true
		}
		completion(false, "name 为空")
		return false
	}
	
}
